import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import '@/assets/css/global.css'
import axios from 'axios'
import store from './store'
import { ElMessage } from 'element-plus'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

axios.defaults.baseURL = 'http://127.0.0.1:9999/common/'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {

    // 在发送请求之前做些什么
    // 判断是否存在token,如果存在将每个页面header添加token
    if (localStorage.getItem("token")) {
        console.log('token', localStorage.getItem("token"))
        config.headers['token'] = localStorage.getItem("token");
    }
    console.log("config", config)
    return config
}, function (error) {
    console.log("error", error)
    router.push('/login')
    return Promise.reject(error)
})



// 拦截返回的数据
axios.interceptors.response.use(response => {
    if(response.data instanceof Blob) return response.data
    console.log("lanjie", response)
    if (response.data.code == "200") {
        return response
    }
    else {
        if (response.data.code >= 4000) {
            if(response.data.code == 4001){
                let originalRequest = response.config;
                refreshToken()
                originalRequest.headers.token =  localStorage.getItem('userInfo')
               return axios(originalRequest)            
            }
            else{
                ElMessage.warning(response.data.message)
            router.replace('/login') 
            }
           

        }
        else {
            ElMessage.error(response.data.message)

        }
        return response

    }
    // 接下来会在这里进行token过期的逻辑处理
}, error => {
    console.log('error', error)
    ElMessage.error(error.response.data.message)
})

async function refreshToken() {
    let userInfo =  JSON.parse(localStorage.getItem('userInfo'))
    const {data:res} = await axios.get('/refreshToken?userName='+userInfo.managerName)
    console.log("refreshtoken",res)
    localStorage.setItem("token",res.data.authorization)
    store.dispatch('chat/connect')
    
}


const app = createApp(App)
app.config.globalProperties.$http = axios
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
app.use(router).use(ElementPlus).use(store).mount('#app')
